import MapboxDraw from '@mapbox/mapbox-gl-draw'
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'
import styles from '@/utils/draw-style/styles.js'
import emitter from '@/utils/event-bus'

class SharedDrawingManager {
  constructor() {
    this.draw = null
    this.map = null
    this.isInitialized = false
    this.eventListeners = new Map()
  }

  init(map) {
    if (this.isInitialized && this.map === map) {
      return this.draw
    }

    this.map = map
    
    // Check if MapboxDraw already exists on this map
    const existingDrawControl = this.getExistingDrawControl(map)
    
    if (existingDrawControl) {
      this.draw = existingDrawControl
      console.log('Using existing MapboxDraw instance')
    } else {
      // Create new MapboxDraw instance
      this.draw = new MapboxDraw({
        keybindings: false,
        touchEnabled: false,
        boxSelect: false,
        displayControlsDefault: false,
        styles,
      })
      
      map.addControl(this.draw)
      console.log('Created new MapboxDraw instance')
    }
    
    this.isInitialized = true
    return this.draw
  }

  getExistingDrawControl(map) {
    // Try to find existing MapboxDraw control
    if (map._controls) {
      for (const control of map._controls) {
        if (control instanceof MapboxDraw) {
          return control
        }
      }
    }
    return null
  }

  getDraw() {
    return this.draw
  }

  isInitialized() {
    return this.isInitialized
  }

  cleanup() {
    if (this.draw && this.map) {
      // Remove event listeners
      this.removeAllEventListeners()
      
      // Don't remove the control as it might be used by other components
      this.draw = null
      this.map = null
      this.isInitialized = false
    }
  }

  addEventListener(event, handler) {
    if (!this.map || !this.draw) return
    
    const key = `${event}_${handler.name || Date.now()}`
    this.eventListeners.set(key, { event, handler })
    this.map.on(event, handler)
  }

  removeEventListener(event, handler) {
    if (!this.map) return
    
    const key = `${event}_${handler.name || Date.now()}`
    const listener = this.eventListeners.get(key)
    if (listener) {
      this.map.off(event, handler)
      this.eventListeners.delete(key)
    }
  }

  removeAllEventListeners() {
    if (!this.map) return
    
    for (const [key, { event, handler }] of this.eventListeners) {
      this.map.off(event, handler)
    }
    this.eventListeners.clear()
  }

}

// Create singleton instance
const sharedDrawingManager = new SharedDrawingManager()

export default sharedDrawingManager 